package hanshunping.project.chatRoom.chatClient.client.service;
/**
 * create by: 蔡博
 * description: TODO
 * create time: 2022/11/20 15:44
 * 用户相关服务方法
 *
 * @Param: null
 * @return
 */

import hanshunping.project.chatRoom.common.Message;
import hanshunping.project.chatRoom.common.MessageType;
import hanshunping.project.chatRoom.common.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class UserService {
    private User u = new User();
    private Socket socket;
    boolean cheack = false;

    public boolean checkUser(String userId, String pwd) {
        u.setUserId(userId);
        u.setPasswd(pwd);

        try {
            socket = new Socket(InetAddress.getLocalHost(), 9999);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(u);

            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            Message ms = (Message) objectInputStream.readObject();
            if (ms.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)) {

                ConnectThread connectThread = new ConnectThread(socket);
                connectThread.start();
                ManageConnectThread.addThread(userId, connectThread);
                cheack = true;
            } else {
                //登录失败，要关闭socket
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cheack;
    }

    public User getU() {
        return u;
    }

    //向服务器端请求在线用户列表
    public void onlineList() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(ManageConnectThread.getThread(u.getUserId()).getSocket().getOutputStream());
            Message ms = new Message();
            ms.setSender(u.getUserId());
            ms.setMesType(MessageType.MESSAGE_ONLINE);
            oos.writeObject(ms);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void logout() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(ManageConnectThread.getThread(u.getUserId()).getSocket().getOutputStream());
            Message ms = new Message();
            ms.setSender(u.getUserId());
            ms.setMesType(MessageType.MESSAGE_EXIT);
            oos.writeObject(ms);
            System.out.println("用户：" + u.getUserId() + "退出系统");
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
